var searchObj = JSON.parse(localStorage.getItem('searchParam'))
$(document).ready(function(){
    if($.cookie('Authorization')===null || localStorage.getItem('realname') === null) {
        showErr("您处于未登录状态，请先登录", '1000000');
        return
    }
    $('#realname').text(localStorage.getItem('realname') )

    
    loadCharacteristicTheme()

    $('.condition-left-bottom').click(function(){
        localStorage.setItem('searchParam', JSON.stringify({
            pageNo: 1,
            pageSize:10
        }))
        window.location.href = host_url + "search.html";
    })

    $('.bar-main-left,.condition-left-top').click(function(){
        localStorage.setItem('searchParam', JSON.stringify({
            pageNo: 1,
            pageSize:10
        }))
        window.location.href = host_url + "theme.html";
    })
    $('.bar-main-right').click(function(){
        window.location.href = host_url + "partner.html";
    })

    $('.search-btn').click(function() {
        if ($('.search-input').val() === '') {
            localStorage.setItem('searchParam', JSON.stringify({
                pageNo: 1,
                pageSize:10
            }))
        } else {
            localStorage.setItem('searchParam', JSON.stringify({
                pageNo: 1,
                pageSize:10,
                entName: $('.search-input').val()
            }))
        }
        window.location.href = host_url + "search.html";
    })

    // 输入框响应回车
    $('.search-input').keyup(function(event){
        if(event.keyCode ==13){
            $('.search-btn').click()
        }
    })

    // 产业园区选择
    $('.parkList-box').on('click', 'li', function(){
        var tempText = $(this).text().split('（')[0]
        $('.parkList-box li').removeClass('active')
        if (searchObj.park === tempText) {
            delete searchObj.park
        } else {
            $(this).addClass('active')
            searchObj.park = tempText
        }
        searchObj.pageNo = 1
        loadCondition()
    })

    // 产业领域选择
    $('.fieldList-box').on('click', 'li', function(){
        var tempText = $(this).text().split('（')[0]
        $('.fieldList-box li').removeClass('active')
        if (searchObj.fieldclass === tempText) {
            delete searchObj.fieldclass
        } else {
            $(this).addClass('active')
            searchObj.fieldclass = tempText
        }
        searchObj.pageNo = 1
        loadCondition()
    })

    // 荣誉资质
    $('.honoraryList-box').on('click', 'li', function(){
        var tempText = $(this).text().split('（')[0]
        delete searchObj.label_national_ht // 国高新
        delete searchObj.label_gazelle // 瞪羚企业
        delete searchObj.label_unicorn // 独角兽企业
        delete searchObj.label_100_project // 十百千企业
        delete searchObj.label_zgc_ht // 中关村高新
        if (!$(this).hasClass('active')) {
            $('.honoraryList-box li').removeClass('active')
            $(this).addClass('active')
            if (tempText === '国高新') searchObj.label_national_ht = '1'
            if (tempText === '瞪羚') searchObj.label_gazelle = '1'
            if (tempText === '独角兽') searchObj.label_unicorn = '1'
            if (tempText === '十百千') searchObj.label_100_project = '1'
            if (tempText === '中关村高新') searchObj.label_zgc_ht = '1'
        } else {
            $('.honoraryList-box li').removeClass('active')
        }
        searchObj.pageNo = 1
        loadCondition()
    })

    // 业务布局选择
    $('.layoutList-box').on('click', 'li', function(){
        var tempText = $(this).text().split('（')[0]
        $('.layoutList-box li').removeClass('active')
        if (searchObj.businessLayout === tempText) {
            delete searchObj.businessLayout
        } else {
            $(this).addClass('active')
            searchObj.businessLayout = tempText
        }
        searchObj.pageNo = 1
        loadCondition()
    })

    // 特色设置
    $('.featureList-box').on('click', 'li', function(){
        var tempText = $(this).text().split('（')[0]
        $('.featureList-box li').removeClass('active')
        if (searchObj.feature === tempText) {
            delete searchObj.feature
        } else {
            $(this).addClass('active')
            searchObj.feature = tempText
        }
        searchObj.pageNo = 1
        loadCondition()
    })

    // 排序
    $('.order-box span').click(function(){
        if ($(this).hasClass('active')) {
            if ($(this).children('i').hasClass('zheng')) {
                $(this).children('i').removeClass('zheng')
                $(this).children('i').addClass('dao')
                searchObj.other_order = $(this).attr('add-data') + '_desc'
            } else if ($(this).children('i').hasClass('dao')){
                $(this).children('i').removeClass('dao')
                $(this).children('i').addClass('zheng')
                $(this).removeClass('active')
                delete searchObj.other_order
            }
        } else {
            $('.order-box span').removeClass('active')
            $('.order-box i').removeClass('dao')
            $('.order-box i').addClass('zheng')
            $(this).addClass('active')
            searchObj.other_order = $(this).attr('add-data') + '_asc'
        }

        searchObj.pageNo = 1
        loadCondition()
    })

     // 关注企业
     $('.list-item-box').on('click', '.collect-x,.collect-y', function() {
        var id = $(this).attr('add-id')
        var that = this
        if (parseInt(id) > 0) {
            $.ajax({
                // url: service_url + '/a/personal/attentEnterprise/attent?eid='+id +'&token=' + $.cookie('Authorization'),
                url: service_url + '/a/zhiku/attentZkEntInfo/attent?eid='+id +'&token=' + $.cookie('Authorization'),
                type: 'GET',
                xhrFields: {
                    withCredentials: true
                },
                crossDomain: true,
                contentType: 'application/json',
                dataType: 'jsonp',
                jsonpCallback:"success_jsonpCallback",  
                processData: false, // 告诉jQuery不要去处理发送的数据
                success: function(data) {
                    if (data.status === '00') {
                        var msg = data.msg
                        if (msg === '关注成功！') {
                            $(that).removeClass('collect-y')
                            $(that).addClass('collect-x')
                        } else if (msg === '取消关注成功！') {
                            $(that).removeClass('collect-x')
                            $(that).addClass('collect-y')
                        }
                        // top.alert(msg,'','',{type: 'success'})

                    } else {
                        showErr(data.msg)
                    }
                },
                error: function(XMLHttpRequest, textStatus, errorThrown) {
                    console.log(XMLHttpRequest, textStatus, errorThrown)
                }
            })
        }
        return false
    })

})

function loadCondition() {
    localStorage.setItem('searchParam', JSON.stringify(searchObj))
    var resultStr = getUrlParamStr(searchObj)

    // 显示搜索企业名称
    $.ajax({
        url: service_url + '/a/zhiku/zkEntInfo/advancedSerach?'+resultStr,
        type: 'GET',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        contentType: 'application/json',
        dataType: 'jsonp',
        jsonpCallback:"success_jsonpCallback",  
        processData: false, // 告诉jQuery不要去处理发送的数据
        success: function(data) {
            if (data.status === "1000000") {
                showErr("您处于未登录状态，请先登录", '1000000')
                return
            }
            if (data.data.length === 0) {
                $('.result-sum').text('0')
                if (searchObj.entName !== undefined) {
                    $('.empty-tip').html('您检索的“<b>'+searchObj.entName+'</b>”不在系统数据库中，<br>前往中关村产业组织平台查看<a href="http://zhizhao.bjzcdi.com:180/" target="_blank">更多信息</a>。')
                } else {
                    $('.empty-tip').html('未检索到结果，<br>前往中关村产业组织平台查看<a href="http://zhizhao.bjzcdi.com:180/" target="_blank">更多信息</a>。')
                }
                $('.search-list-empty').show()
                $('.list-item-box, .pagination-box').hide()
            } else {
                $('.result-sum').text(data.count)
                $('.list-item-box').empty()
                $('.pagination').jqPaginator({
                    totalCounts: data.count,
                    pageSize: searchObj.pageSize,
                    visiblePages: 10,
                    currentPage: searchObj.pageNo,
                    first: '<li class="first"><a href="javascript:void(0);">首页<\/a><\/li>',
                    prev: '<li class="prev"><a href="javascript:void(0);">&laquo;<\/a><\/li>',
                    next: '<li class="next"><a href="javascript:void(0);">&raquo;<\/a><\/li>',
                    last: '<li class="last"><a href="javascript:void(0);">末页<\/a><\/li>',
                    page: '<li class="page"><a href="javascript:void(0);">{{page}}<\/a><\/li>',
                    onPageChange: function (num, type) {
                        if (type === 'change') {
                            searchObj.pageNo = num
                            loadCondition()
                        }
                    }
                });
                $('.pagination-box').show()
                
                
                var tempHtml = ''
                for (var m = 0; m < data.data.length; m++) {
                    var item = data.data[m]
                    var regcap = item.regcap / 10000 >= 1 ? (item.regcap / 10000) + '亿元' : item.regcap + '万元'
                    var attentHtml = ''
                    if (item.isAttent) {
                        attentHtml = '<span class="collect-x" add-id="'+item.id+'"></span>'
                    } else {
                        attentHtml = '<span class="collect-y" add-id="'+item.id+'"></span>'
                    }
                    tempHtml = tempHtml + '<div class="list-item"><a href="detail.html?id='+item.id+'" target="_blank"><h2>'+item.entName+attentHtml+'</h2></a><div class="tag-box"><span class="tag-span1">'+item.esdateStr+'</span><span class="tag-span2">'+regcap+'</span>'

                    if (item.field !== undefined) {
                        var field = item.field
                        fieldArr = field.split(',')
                        for (var i = 0; i < fieldArr.length; i++) {
                            if (fieldArr[i] !== '') tempHtml = tempHtml + '<span  class="tag-span3">'+fieldArr[i]+'</span>'
                        }
                    }
                    tempHtml = tempHtml + '</div>'

                    // var description = item.description || ''
                    // tempHtml = tempHtml + '</div><p>'+description+'</p></div>'

                    var tempNum = 0
                    for (var x = 0; x < item.linkList.length; x++) {
                        if (item.linkList[x].description !== undefined && item.linkList[x].description !== '' && tempNum < 2) {
                            tempNum ++
                            tempHtml = tempHtml + '<p>'+item.linkList[x].description+'</p>'
                        }
                        
                    }
                    tempHtml = tempHtml + '</div>'
                }
                $('.list-item-box').append(tempHtml)
                $('.list-item-box').show()
                $('.search-list-empty').hide()
            }

        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(XMLHttpRequest, textStatus, errorThrown)
        }
    })
}

// 加载特色主题数量
function loadCharacteristicTheme() {
    $.ajax({
        url: service_url + '/a/zhiku/zkEntInfo/countCharacteristicTheme?token=' + $.cookie('Authorization'),
        type: 'GET',
        xhrFields: {
            withCredentials: true
        },
        crossDomain: true,
        contentType: 'application/json',
        dataType: 'jsonp',
        jsonpCallback:"success_jsonpCallback",  
        processData: false, // 告诉jQuery不要去处理发送的数据
        success: function(data) {


            $('.parkList-box').empty()
            var tempHtml = ''
            var parkArr = [
                {
                    park: '软件园',
                    num: 0
                },
                {
                    park: '生命科学园',
                    num: 0
                },
                {
                    park: '集成电路设计园',
                    num: 0
                },
                {
                    park: '高端医疗器械园',
                    num: 0
                },
                {
                    park: '东升科技园',
                    num: 0
                }
            ]
            for (var j = 0; j < parkArr.length; j++) {
                for (var i = 0; i < data.parkList.length; i++) {
                    if (parkArr[j].park === data.parkList[i].park) {
                        parkArr[j].num = data.parkList[i].num
                    }
                }
                tempHtml = tempHtml + '<li>'+parkArr[j].park+'（'+parkArr[j].num+'）</li>'
            }
            $('.parkList-box').append(tempHtml)

            $('.fieldList-box').empty()
            tempHtml = ''
            tempHtml = tempHtml  + '<li>新一代信息产业（'+data.fieldList[0].xxcyNum+'）</li>'
            tempHtml = tempHtml  + '<li>人工智能（'+data.fieldList[0].rgznNum+'）</li>'
            tempHtml = tempHtml  + '<li>生物医药（'+data.fieldList[0].swyyNum+'）</li>'
            tempHtml = tempHtml  + '<li>医疗器械（'+data.fieldList[0].ylqxNum+'）</li>'
            tempHtml = tempHtml  + '<li>集成电路（'+data.fieldList[0].jcdlNum+'）</li>'
            tempHtml = tempHtml  + '<li>智能制造（'+data.fieldList[0].znzzNum+'）</li>'
            tempHtml = tempHtml  + '<li>新能源汽车（'+data.fieldList[0].xnyqcNum+'）</li>'
            tempHtml = tempHtml  + '<li>节能环保（'+data.fieldList[0].jnhbNum+'）</li>'
            tempHtml = tempHtml  + '<li>新能源（'+data.fieldList[0].xnyNum+'）</li>'
            tempHtml = tempHtml  + '<li>新材料（'+data.fieldList[0].xclNum+'）</li>'
            tempHtml = tempHtml  + '<li>科技服务（'+data.fieldList[0].kjfwNum+'）</li>'
            // tempHtml = tempHtml  + '<li>其他（'+data.fieldList[0].otherNum+'）</li>'
            $('.fieldList-box').append(tempHtml)

            $('.honoraryList-box').empty()
            tempHtml = ''
            tempHtml = tempHtml  + '<li>国高新（'+data.honoraryList[0].nationalNum+'）</li>'
            tempHtml = tempHtml  + '<li>瞪羚（'+data.honoraryList[0].dlNum+'）</li>'
            tempHtml = tempHtml  + '<li>独角兽（'+data.honoraryList[0].unicornNum+'）</li>'
            tempHtml = tempHtml  + '<li>十百千（'+data.honoraryList[0].sbqNum+'）</li>'
            tempHtml = tempHtml  + '<li>中关村高新（'+data.honoraryList[0].zgcNum+'）</li>'
            $('.honoraryList-box').append(tempHtml)

            $('.layoutList-box').empty()
            tempHtml = ''
            tempHtml = tempHtml  + '<li>京津冀（'+data.layoutList[0].jjjNum+'）</li>'
            tempHtml = tempHtml  + '<li class="single">北京（'+data.layoutList[0].bjNum+'）</li>'
            tempHtml = tempHtml  + '<li>长三角（'+data.layoutList[0].csjNum+'）</li>'
            tempHtml = tempHtml  + '<li class="single">上海（'+data.layoutList[0].shNum+'）</li>'
            tempHtml = tempHtml  + '<li>粤港澳大湾区（'+data.layoutList[0].ygaNum+'）</li>'
            tempHtml = tempHtml  + '<li class="single">广州（'+data.layoutList[0].gzNum+'）</li>'
            tempHtml = tempHtml  + '<li>长江经济带（'+data.layoutList[0].cjNum+'）</li>'
            tempHtml = tempHtml  + '<li>中部崛起（'+data.layoutList[0].zbNum+'）</li>'
            // tempHtml = tempHtml  + '<li>其他（'+data.layoutList[0].otherNum+'）</li>'
            $('.layoutList-box').append(tempHtml)

            $('.featureList-box').empty()
            tempHtml = ''
            tempHtml = tempHtml  + '<li>上市/IPO（'+data.featureList[0].ssipoNum+'）</li>'
            tempHtml = tempHtml  + '<li>股权链接（'+data.featureList[0].gqljNum+'）</li>'
            tempHtml = tempHtml  + '<li>有合作需求（'+data.featureList[0].hzxqNum+'）</li>'
            $('.featureList-box').append(tempHtml)

            // 恢复刷新前的搜索条件
            loadCondition()
            recoverCondition()
            
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {}
    })
}


// 恢复检索条件
function recoverCondition() {

    if (searchObj.park !== undefined) {
        $('.parkList-box li').each(function(index,item){
            if ($(item).text().indexOf(searchObj.park) > -1) {
                $(item).addClass('active')
            }
        })
    }

    if (searchObj.fieldclass !== undefined) {
        $('.fieldList-box li').each(function(index,item){
            if ($(item).text().indexOf(searchObj.fieldclass) > -1) {
                $(item).addClass('active')
            }
        })
    }

    if (!(searchObj.label_national_ht === undefined && searchObj.label_gazelle === undefined && searchObj.label_unicorn === undefined && searchObj.label_100_project === undefined && searchObj.label_zgc_ht === undefined)) {
        if (searchObj.label_national_ht !== undefined) {
            $('.honoraryList-box li:eq(0)').addClass('active')
        }
        if (searchObj.label_gazelle !== undefined) {
            $('.honoraryList-box li:eq(1)').addClass('active')
        }
        if (searchObj.label_unicorn !== undefined) {
            $('.honoraryList-box li:eq(2)').addClass('active')
        }
        if (searchObj.label_100_project !== undefined) {
            $('.honoraryList-box li:eq(3)').addClass('active')
        }
        if (searchObj.label_zgc_ht !== undefined) {
            $('.honoraryList-box li:eq(4)').addClass('active')
        }
    }

    if (searchObj.businessLayout !== undefined) {
        $('.layoutList-box li').each(function(index,item){
            if ($(item).text().indexOf(searchObj.businessLayout) > -1) {
                $(item).addClass('active')
            }
        })
    }


    if (searchObj.feature !== undefined) {
        $('.featureList-box li').each(function(index,item){
            if ($(item).text().indexOf(searchObj.feature) > -1) {
                $(item).addClass('active')
            }
        })
    }

    if (searchObj.other_order !== undefined) {
        $('.order-box span').each(function(index,item){
            if ($(item).attr('add-data').indexOf(searchObj.other_order) > -1) {
                $(item).addClass('active')
            }
        })
    }
}